package io.github.ali.commons.code;


/**
 * 统一响应类
 * 
 * @author fuli
 * @date 2018年6月23日
 * @version 1.0.0
 */
public class Result {
	private String code;
	private String message;
	private Object data;

	private Result(RespCode respCode) {
		this.code = respCode.getCode();
		this.message = respCode.getMessage();
	}

	private Result(RespCode respCode, Object data) {
		this.code = respCode.getCode();
		this.message = respCode.getMessage();
		this.data = data;
	}

	private Result(String code, String message) {
		this.code = code;
		this.message = message;
	}

	public String getCode() {
		return code;
	}

	public String getMessage() {
		return message;
	}

	public <T>T getData() {
		return (T)data;
	}

	public void setData(Object data) {
		this.data = data;
	}
	
	public boolean isSuccessful() {
		return SUCCESS.code.equals(code);
	}

	private static RespCode SUCCESS_RESP_CODE = null;
	private static RespCode FAILED_RESP_CODE = null;
	private static Result SUCCESS = null;
	private static Result FAILED = null;

	/**
	 * 填充成功/失败响应码
	 *
	 * @param SUCCESS_RESP_CODE
	 * @param FAILED_RESP_CODE
	 */
	static void fillSuccessRespCodeAndFailedRespCode(RespCode SUCCESS_RESP_CODE, RespCode FAILED_RESP_CODE) {
		if (Result.SUCCESS == null) {
			Result.SUCCESS_RESP_CODE = SUCCESS_RESP_CODE;
			Result.FAILED_RESP_CODE = FAILED_RESP_CODE;
			Result.SUCCESS = new Result(SUCCESS_RESP_CODE);
			Result.FAILED = new Result(FAILED_RESP_CODE);
		}
	}

	/**
	 * 构建成功响应
	 * 若未自定义RespCode则返回空
	 * @return
	 */
	public static Result buildSuccess(){
		return SUCCESS;
	}
	public static Result buildSuccess(Object data) {
		return new Result(SUCCESS_RESP_CODE, data);
	}

	/**
	 * 构建失败响应
	 * 若未自定义RespCode则返回空
	 * @return
	 */
	public static Result buildFailed(){
		return FAILED;
	}
	public static Result buildFailed(Object data) {
		return new Result(FAILED_RESP_CODE, data);
	}

	public static Result build(RespCode respCode, Object data) {
		return new Result(respCode, data);
	}
	public static Result build(String code, String message) {
		return new Result(code, message);
	}
}
